package Servlet;

import bean.Message;
import bean.User;
import dao.MessageDao;
import dao.UserDao;
import net.sf.json.JSONArray;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet(name = "chatRefresh", value = "/chatRefresh")
public class chatRefresh extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = null;
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("Id");
        List<String> friendID ;
        MessageDao messageDao = new MessageDao();
        List<User> firends = new ArrayList<>();
        UserDao userDao = new UserDao();
        ArrayList<Message> personalizes = null;
        ArrayList<ArrayList<Message>> personalMessages  = new ArrayList<>() ;
        friendID = userDao.findAllFriend(id);
        List<Integer> listnumber = new ArrayList<>();

        for(int i = 0 ; i < friendID.size() ; i++){
            user = userDao.findUser(friendID.get(i));
            firends.add(user);
            personalizes =  messageDao.listAllPersonalMassage(id,friendID.get(i));
            personalizes.sort(Comparator.comparingLong(Message::getSendTime));
            System.out.println("2222"+personalizes);
            listnumber.add(personalizes.size());
            personalMessages.add(personalizes);
        }
        System.out.println("333"+personalMessages);
        ArrayList<Message> list = new ArrayList<>();
        for (int k = 0; k < friendID.size(); k++) {
            for (int j = 0; j < listnumber.get(k) ; j++) {
                list.add(personalMessages.get(k).get(j));
            }
        }
        System.out.println(list);
        System.out.println(list);
        JSONArray jsonArray = new JSONArray();
        Map map = new HashMap<String , List<Object>>();
        map.put("friends" , firends );
        map.put("message", list);
        PrintWriter out = response.getWriter();
        out.print(jsonArray.fromObject(map));
//        out.print(jsonArray1.fromObject(list));

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
